#ifndef CEPOLLSERVERMGR_H
#define CEPOLLSERVERMGR_H

#include <QObject>
#include <QThreadPool>
#include <QMutexLocker>
#include <QMap>
#include <arpa/inet.h>

#include "tcpstruct.h"

class CLogOper;
class CEpollServerThread;
class CServerWorkThread;

class CEpollServerMgr : public QObject
{
    Q_OBJECT
public:
    //服务端运行状态
    enum enumServerStatus
    {
        enServerStopped = 0,    //停止
        enServerRunning,        //运行中
    };
public:
    explicit CEpollServerMgr(QObject* parent = nullptr);
    virtual ~CEpollServerMgr();
    bool startServer(int nPort);                //启动
    void stopServer();                          //停止
    void setThreadPoolSize(int nSize);          //设置线程池上限

private:
    void init();

signals:
    void sigLogMsg(const int&, const QString&); //日志
    void sigServerStatusChanged(int);           //服务端运行状态变化
    void sigClientStatusChanged(QString sGuid, bool bState);    //客户端运行状态变化

private slots:
    //建立新客户端连接
    void slotHandleNewConnection(int nClientFd, sockaddr_in* stClientAddr);
    //等待读取数据
    void slotHandleReadReady(int nFd);
    //关闭连接
    void slotHandleConnectionClosed(int nFd);
    //服务端通信日志
    void slotHandleServerLogMsg(const int& nLevel, const QString& sMod, const QString& sMsg);
    //报文解析日志
    void slotHandleWorkLogMsg(const int& nFd, const int& sLevel, const QString& sMod, const QString& sMsg);

private:
    QMutex                  m_mutex;
    CLogOper*               m_pLog;
    CEpollServerThread*     m_pServerThread;    //服务端线程
    QThreadPool             m_threadPool;       //线程池
    QMap<int, SClientCfg>   m_mapClient;        //客户端编号与配置对照
};

#endif // CEPOLLSERVERMGR_H
